﻿namespace MvcWebRole4.Utility
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Web;

    public static class Crypto
    {
        /// <summary>
        /// Encrypt the given string using public key.
        /// </summary>
        /// <param name="plainText">The text to encrypt.</param>
        public static string Encrypt(string plainText)
        {
            const string publicKey = "BgIAAACkAABSU0ExAAQAAAEAAQADcTEJMRF9A0SbfBLrnnuTFC2wDa/i1k7xsbWO5V1EeMslK07c58FyvYQsBi4dRyYKYiKwD1MxgXIduTO7WhjgHzk9zVwQNHRZBd2BRe4p0TJCYEJjQ1qtXdxLJ58+MhSRSTnkfATDTX3qI5gyQFwQtvgOPNghJa//rpNhnulZ3w==";

            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }

            string outStr = null;
            var keyBlob = Convert.FromBase64String(publicKey);

            using (var provider = new RSACryptoServiceProvider())
            {
                provider.ImportCspBlob(keyBlob);

                var content = Encoding.UTF8.GetBytes(plainText);
                var encrypted = provider.Encrypt(content, false);

                outStr = Convert.ToBase64String(encrypted);
            }

            return outStr;
        }

        /// <summary>
        /// Decrypt the given string.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        public static string Decrypt(string cipherText)
        {
            const string privateKey = "";

            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException("cipherText");
            }

            string outStr = null;
            var keyBlob = Convert.FromBase64String(privateKey);

            using (var provider = new RSACryptoServiceProvider())
            {
                provider.ImportCspBlob(keyBlob);

                var content = Convert.FromBase64String(cipherText);
                var decrypted = provider.Decrypt(content, false);

                outStr = Encoding.UTF8.GetString(decrypted);
            }

            return outStr;
        }
    }
}